/**
 * Copyright (c) 2008, Julien PORTALIER
 * http://featherphp.googlecode.com/
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

Dialog.Frame = new Class(
{
	Extends: Dialog.Window,
	ajax:    null,
	
	initialize: function(url, options)
	{
		this.setOptions({
			'divertLinks': true,
			'divertForms': true,
			'callback':    $empty
		});
		this.parent(options);
		this.request(url);
	},
	
	request: function(url, method, data)
	{
		if (!this.ajax)
		{
			// prepares the request
			this.ajax = new Request({
				'autoCancel': true,
				'onComplete': this.replaceContent.bind(this)
			});
		}
		
		// makes the request
		this.ajax.setOptions({
			'method': method || 'get',
			'url':    url,
			'data':   data
		}).send();
	},
	
	replaceContent: function(html)
	{
		this.setContent('html', html);
		this.divertLinks();
	},
	
	divertLinks: function()
	{
		if (this.options.divertLinks)
		{
			// diverts links
			this.content.getElements('a').each(function(a)
			{
				if (!a.hasClass('no-divert')) {
					a.addEvent('click', this.followLink.bindWithEvent(this));
				}
			}, this);
		}
		if (this.options.divertForms)
		{
			// diverts forms
			this.content.getElements('form').each(function(form)
			{
				if (!form.hasClass('no-divert')) {
					form.addEvent('submit', this.postForm.bindWithEvent(this));
				}
			}, this);
		}
		
		// caller's own divert functions
		this.options.callback(this.content);
	},
	
	followLink: function(evt)
	{
		evt.stop();
		this.request(evt.target.get('href'));
	},
	
	postForm: function(evt)
	{
		var form = evt.target;
		if (form.get('enctype') == 'multipart/form-data')
		{
			// uploads in a hidden iframe
			this.hidden_iframe = new Element('iframe', {
				'name': 'dialog-frame-upload-iframe',
				'styles': {
					'display':    'none',
					'visibility': 'hidden'
				}
			}).injectInside(document.body);
			
			// target post to hidden iframe
			form.set('target', 'dialog-frame-upload-iframe');
			
			// event (when file has been uploaded)
			this.hidden_iframe.addEvent('load', this.afterUpload.bind(this));
		}
		else
		{
			// classic form 
			evt.stop();
			this.request(form.get('action'), form.get('method'), form.toQueryString());
		}
	},
	
	afterUpload: function()
	{
		// returned content
		var xbody = this.hidden_iframe.contentDocument ?
			this.hidden_iframe.contentDocument.body :
			document.frames['dialog-frame-upload-iframe'].document.body;
		var content = xbody;
		
		// set content in dialog
		this.replaceContent(content.innerHTML);
		
		// destroys iframe
		this.hidden_iframe.destroy.delay(10, this.hidden_iframe);
	}
});
